package com.hzcc.hzccblog.shiro;

import com.hzcc.hzccblog.common.enums.LoginEnums;
import com.hzcc.hzccblog.module.dao.UserDao;
import com.hzcc.hzccblog.module.entity.po.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

/**
 * @Author 早睡蛋
 * @Date 2022/6/6 19:48:59
 * @Desc:自定义Realm
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("————身份认证方法————");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 从数据库获取对应用户名密码的用户
        User userInfo = userDao.getUserByEmail((String) token.getPrincipal());
        if (null == userInfo) {
            throw new UnknownAccountException (LoginEnums.LOGIN_FAIL.getMessage());
        }
        String salt = userInfo.getSalt();
        String userPwd = new String((char[]) token.getCredentials());
        String userPassword = userInfo.getPassword();
        String pwd = DigestUtils.md5DigestAsHex((userPwd+salt).getBytes());
        if (!pwd.equals(userPassword)) {
            throw new AccountException(LoginEnums.LOGIN_FAIL.getMessage());
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), userPwd, getName());
    }
}
